/**
 * @Project Name:hoofungson-elk-log
 * @Package Name:cn.hoofungson.framework.elk.log.converter.pattern
 * @Since JDK 1.8
 */

package cn.hoofungson.framework.elk.log.converter.pattern;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @Description: ExceptionPatternConverter
 * @Author 胡松 hoofungson@163.com
 * @Date 2020-03-07 18:28
 * @Version V1.0
 */
public class ExceptionPatternConverter extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        if (null != iLoggingEvent.getThrowableProxy()) {
            StringBuffer exceptionStringBuffer = new StringBuffer();
            exceptionStringBuffer.append(iLoggingEvent.getThrowableProxy().getClassName());
            exceptionStringBuffer.append(": ");
            exceptionStringBuffer.append(iLoggingEvent.getThrowableProxy().getMessage());
            exceptionStringBuffer.append("\n ");
            StackTraceElementProxy[] stackTraceElementProxies = iLoggingEvent.getThrowableProxy().getStackTraceElementProxyArray();
            if (ArrayUtils.isNotEmpty(stackTraceElementProxies)) {
                for (StackTraceElementProxy stackTraceElementProxy : stackTraceElementProxies) {
                    exceptionStringBuffer.append("  ");
                    exceptionStringBuffer.append(stackTraceElementProxy.toString());
                    exceptionStringBuffer.append("\n ");
                }
                return exceptionStringBuffer.toString();
            }
        } else {
            return StringUtils.EMPTY;
        }
        return StringUtils.EMPTY;
    }
}
